package com.club.football.config.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.club.football.common.UserHolder;
import com.club.football.dto.UsersDto;
import com.club.football.utils.JwtHelper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.club.football.common.CommonConstants.TOKEN;
import static com.club.football.utils.JwtHelper.checkToken;


/**
 * 刷新令牌拦截器
 *
 * @author gh
 * @date 2023/09/19
 */
@Component
public class RefreshTokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        
        //获取请求头中的token
        String token = request.getHeader(TOKEN);
        if (StringUtils.isBlank(token)) {
            return true;
        }
        //判断tokenKey是否存在
        if (!checkToken(token)) {
            //不存在，跳过此拦截器
            return true;
        }
        UsersDto usersDto = JwtHelper.getUser(token);
        if (usersDto == null) {
            // 没有，需要拦截，设置状态码
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            //拦截
            return false;
        }
        //存在，保存用户信息到 ThreadLocal
        UserHolder.saveUser(usersDto);
        //放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        //移除用户
        UserHolder.removeUser();
    }
}
